<?php

/**
 * commandPayTradeCreate	指令到帐创建订单	接口
 * Date: 2016/11/24 14:34
 */

function testResponse(){

    $config = $GLOBALS['config'];
    $user = $GLOBALS['user'];


    $objReq = new \yijipay\message\request\CommandPayTradeCreateRequest();

    //请求公共部分
    $objReq->setReturnUrl(getReturnUrl());
    $objReq->setNotifyUrl(getNotifyUrl());
    //partnerId默认yijipay\config.php中已经配置
    //$objReq->setPartnerId($config['partnerId']); 
    $objReq->setMerchOrderNo("T" . genOrderNo());
    $objReq->setOrderNo("RID".genOrderNo());
    //signType默认MD5
    $objReq->setSignType("RSA");
    //$objReq->setContext("");


    //构建交易参数
    $item1 = genCommandPayOrder($user);
    //$item2 = genTradeInfo();
    $objReq->setBuyerOrgName("买家PHP");
    $objReq->setBuyerRealName("买家PHP");
    $objReq->setBuyerUserId($user['buyer_uid_yiji']);
    $objReq->setOutUserId($user['buyer_id']);
    $objReq->setCommandPayOrders([$item1]);

    echo "================request: preSignStr：";
    echo "<br/>". \yijipay\SignHelper::getPreSignStr($objReq);

    //构建请求
    $client = new \yijipay\YijiPayClient($config);
    

    $response = $client->execute($objReq);
    echo $response;
    $resp = json_decode($response);

    if($client->verify($response) && $resp->success){
        //循环订单创建结果
        foreach($resp->creatTradeResult as $vo){
            if('SUCCESS' == $vo->creatResult){  //订单创建成功
                //================================
                // 此处填写创建成功的代码
                //================================
                echo "<br/>建单成功[" . $vo->merchOrderNo . "]:";
                echo "<br/>" . json_encode($vo, JSON_UNESCAPED_UNICODE);
            }else if('FAIL' == $vo->creatResult){
                //================================
                // 此处填写创建成功的代码
                //================================
                echo "<br/>建单失败[" . $vo->merchOrderNo . "]:";
                echo "<br/>" . json_encode($vo, JSON_UNESCAPED_UNICODE);
            }
        }
    }else{
        throw new Exception($resp->resultMessage);
    }


}


function genCommandPayOrder($user){
    $order = new \yijipay\message\request\dto\CommandPayOrder();

    $order->setMerchOrderNo("MON". genOrderNo());
    $order->setTradeName("购买电脑");
    $order->setSellerUserId($user['seller_uid_yiji']);
    $order->setPactNo("");
    $order->setTradeAmount("84.51");

    $order->setGoodsTypeCode("5146854");
    $order->setGoodsTypeName("计算机");
    $order->setGoodsName("笔记本电脑");

    $order->setMemo("备注");
    $order->setSellerOrgName("猪八戒科技有限公司");
    $order->setAutoCloseDuration("14400");

    return $order;
}